package cn.westv.scps.web.controller.sysmsg;

import java.io.IOException;
import java.io.InputStream;
import java.net.ConnectException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import cn.westv.scps.connTools.ProxyConnExec;
import cn.westv.scps.constant.ConfigCodeConstant;
import cn.westv.scps.domain.AreaSeverEntity;
import cn.westv.scps.domain.SysMassageSendRecordEntity;
import cn.westv.scps.domain.SysMessageEntity;
import cn.westv.scps.service.areaserver.IAreaServerService;
import cn.westv.scps.service.sysmsg.ISysMsgService;
import cn.westv.scps.utils.Page;
import cn.westv.scps.web.controller.base.AbstractController;
import cn.westv.scps.web.controller.sysmsg.vo.SysMsgVo;

/**
 * 系统消息管理
 * 
 * @author Administrator
 *
 */
@Controller
@RequestMapping("/sys/msg")
public class SysMsgController extends AbstractController<SysMsgController> {

	@Autowired
	private ISysMsgService sysMsgService;
	@Resource
	IAreaServerService areaServerService;

	@RequestMapping("/index.cgi")
	public String toIndex_cgi() {
		return "forward:/WEB-INF/page/sys/sysmsg/msgIndex.jsp";
	}

	@RequestMapping("/edit.cgi")
	public String toEdit_cgi() {
		return "forward:/WEB-INF/page/sys/sysmsg/msgEdit.jsp";
	}

	/**
	 * 分页查找系统消息（结果集只包含SysMessageEntity中的属性）
	 * 
	 * @param sysMsgVo
	 * @param page
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/pagelist")
	public Map<String, Object> sysMsgFindPage(SysMsgVo sysMsgVo, Page<SysMessageEntity> page) {
		try {
			String hql = "from SysMessageEntity where 1 = 1 ";
			List<Object> paramList = new ArrayList<Object>();
			Date beginTime = sysMsgVo.getBeginTime();
			Date endTime = sysMsgVo.getEndTime();

			if (sysMsgVo.getSysMessageEntity() != null) {
				SysMessageEntity sysMessageEntity = sysMsgVo.getSysMessageEntity();

				// 拼接查询条件
				String sysMessageId = sysMessageEntity.getSysMessageId();
				if (StringUtils.isNotBlank(sysMessageId)) {
					hql += " and " + " sysMessageId = ?";
					paramList.add(sysMessageId);
				}
				String title = sysMessageEntity.getTitle();
				if (StringUtils.isNotBlank(title)) {
					hql += " and" + " title like ?";
					paramList.add("%" + title + "%");
				}
				String code = sysMessageEntity.getCode();
				if (StringUtils.isNotBlank(code)) {
					hql += " and " + " code = ?";
					paramList.add(code);
				}
				String payload = sysMessageEntity.getPayload();
				if (StringUtils.isNotBlank(payload)) {
					hql += " and" + " payload like ?";
					paramList.add("%" + payload + "%");
				}
				String redirectUrl = sysMessageEntity.getRedirectUrl();
				if (StringUtils.isNotBlank(redirectUrl)) {
					hql += " and " + " redirectUrl = ?";
					paramList.add(redirectUrl);
				}
				String content = sysMessageEntity.getContent();
				if (StringUtils.isNotBlank(content)) {
					hql += " and " + " content like ?";
					paramList.add("%" + content + "%");
				}
				Integer contentIsEmpty = sysMessageEntity.getContentIsEmpty();
				if (contentIsEmpty != null) {
					hql += " and " + " contentIsEmpty = ?";
					paramList.add(contentIsEmpty);
				}
				Integer state = sysMessageEntity.getState();
				if (state != null) {
					hql += " and " + " state = ?";
					paramList.add(state);
				}
				if (beginTime != null) {
					hql += " and " + " createTime > ?";
					paramList.add(beginTime);
				}
				if (endTime != null) {
					hql += " and " + " createTime < ?";
					paramList.add(endTime);
				}

			}
			Page<SysMessageEntity> findPage = sysMsgService.findPage(hql, page, SysMessageEntity.class,
					paramList.toArray());
			List<SysMessageEntity> results = findPage.getResults();// 获取结果中的系统消息

			if (results != null && results.size() > 0) {
				for (SysMessageEntity sysMessageEntity : results) {
					// 解决映射死循环问题
					// sysMessageEntity.setSysMassageSendRecordEntitys(null);
					Set<SysMassageSendRecordEntity> sysMassageSendRecordEntitys = sysMessageEntity
							.getSysMassageSendRecordEntitys();

					for (SysMassageSendRecordEntity sysMassageSendRecordEntity : sysMassageSendRecordEntitys) {
						sysMassageSendRecordEntity.setAreaSevers(null);
						sysMassageSendRecordEntity.setSysMessageEntity(null);
					}
				}
			}
			// System.out.println(JSON.parseObject(JSON.toJSONString(findPage)));
			// System.out.println(findPage);
			return ajaxReturnMap(OP_STATUS_SUCCESS, "", findPage);
		} catch (Exception e) {
			logErr(e);
			return ajaxReturnMap(OP_STATUS_FAILD, returnMsg(ConfigCodeConstant.UNKNOWN_ERR), null);
		}
	}

	/**
	 * 根据系统消息编码判断 该系统消息是否存在
	 * 
	 * @param code
	 * @return
	 */
	public boolean existMsg(String code) {
		List<SysMessageEntity> find = sysMsgService.find("from SysMessageEntity where code = ?", SysMessageEntity.class,
				new Object[] { code });
		if (find != null && find.size() > 0) {
			return true;
		}
		return false;

	}

	/**
	 * 保存（增加或修改）
	 * 
	 * @param sysMsgVo
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/save")
	public Map<String, Object> saveSysMsg(SysMsgVo sysMsgVo) {
		try {
			if (sysMsgVo != null) {
				String msg = "";// 结果提示
				if (sysMsgVo.getSysMessageEntity() != null) {
					SysMessageEntity sysMessageEntity = sysMsgVo.getSysMessageEntity();// 页面传入的信息
					// SysMessageEntity sysMessageEntityDB = new
					// SysMessageEntity();// 最终保存的数据

					String sysMessageId = sysMessageEntity.getSysMessageId();
					if (StringUtils.isEmpty(sysMessageId)) {// 系统消息id为空 --新增
						// sysMessageEntityDB = sysMessageEntity;
						Date date = new Date();
						sysMessageEntity.setCreateTime(date);

						String code = sysMessageEntity.getCode();
						if (existMsg(code)) {
							return ajaxReturnMap(OP_STATUS_FAILD, "添加失败，系统消息编码已存在！", code);
						}
						msg = ConfigCodeConstant.ADD_SUCCEED;
						sysMsgService.save(sysMessageEntity);
					} else {// id不为空--修改
						// sysMessageEntityDB =
						// sysMsgService.get(SysMessageEntity.class,
						// sysMessageId);// 获取原消息
						msg = ConfigCodeConstant.UPDATE_SUCCEED;
						sysMsgService.update(sysMessageEntity);
					}
				}
				return ajaxReturnMap(OP_STATUS_SUCCESS, msg, null);
			} else {
				return ajaxReturnMap(OP_STATUS_FAILD, "保存失败！", null);
			}

		} catch (Exception e) {
			logErr(e);
			return ajaxReturnMap(OP_STATUS_FAILD, returnMsg(ConfigCodeConstant.UNKNOWN_ERR), null);
		}
	}

	/**
	 * 根据id删除消息
	 * 
	 * @param ids
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/del")
	public Map<String, Object> delSysMsg(String ids) {
		try {
			String[] idArr = null;
			if (StringUtils.isNotBlank(ids)) {
				idArr = ids.split(","); // 根据id批量删除，id之间使用","分隔
			}
			String msg = "";
			sysMsgService.delete(SysMessageEntity.class, idArr);
			msg = ConfigCodeConstant.DEL_SUCCEED;
			return ajaxReturnMap(OP_STATUS_SUCCESS, msg, null);
		} catch (Exception e) {
			logErr(e);
			return ajaxReturnMap(OP_STATUS_FAILD, returnMsg(ConfigCodeConstant.UNKNOWN_ERR), null);
		}
	}

	/**
	 * 根据id查找系统消息
	 * 
	 * @param sysMsgId
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/detail")
	public Map<String, Object> detailSysMsg(String id) {
		if (StringUtils.isEmpty(id)) {
			return ajaxReturnMap(OP_STATUS_FAILD, ConfigCodeConstant.REQUIRED_PARAMETERS_IS_NULL + "（id为空）", null);
		}
		SysMessageEntity sysMessageEntity = sysMsgService.get(SysMessageEntity.class, id);
		if (sysMessageEntity != null) {
			Set<SysMassageSendRecordEntity> sysMassageSendRecordEntitys = sysMessageEntity
					.getSysMassageSendRecordEntitys();
			for (SysMassageSendRecordEntity sysMassageSendRecordEntity : sysMassageSendRecordEntitys) {
				sysMassageSendRecordEntity.setAreaSevers(null);
				sysMassageSendRecordEntity.setSysMessageEntity(null);
			}

			return ajaxReturnMap(OP_STATUS_SUCCESS, "", sysMessageEntity);
		} else {
			return ajaxReturnMap(OP_STATUS_FAILD, "id不存在!", null);
		}
	}

	/**
	 * 小米推送消息后，发送回执的回调接口
	 * 
	 * @param mobile
	 */
	@RequestMapping("/callback")
	public void miPushCallback(HttpServletRequest request) {
		InputStream in = null;
		try {
			in = request.getInputStream();
			byte[] b = new byte[1024];
			int len = 0;
			String str = "";
			while ((len = in.read(b)) != -1) {
				str += new String(b, 0, len);
			}
			// if (StringUtils.isNotBlank(str))
			logger.info("小米推送回调内容:" + str);
		} catch (Exception e) {
			logErr(e);
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

	}

	/**
	 * 同步系统消息表到所有的服务器
	 * 
	 * @param ids
	 *            服务器id
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/synupdate")
	public Map<String, Object> synchronismUpdateSysMessageToCloudBase(String ids) {
		try {
			List<AreaSeverEntity> areaSeverEntityList = null;
			if (StringUtils.isNotBlank(ids)) {
				String[] idArr = ids.split(","); // id之间使用","分隔
				areaSeverEntityList = new ArrayList<>();
				if (idArr.length > 0) {
					for (String id : idArr) {
						AreaSeverEntity entity = areaServerService.get(AreaSeverEntity.class, id);
						areaSeverEntityList.add(entity);
					}
				}

			} else {
				areaSeverEntityList = areaServerService.find("from AreaSeverEntity", AreaSeverEntity.class, null);
			}
			List<SysMessageEntity> sysMessageEntities = sysMsgService.find("from SysMessageEntity",
					SysMessageEntity.class, null);
			for (SysMessageEntity sysMessageEntity : sysMessageEntities) {
				sysMessageEntity.setSysMassageSendRecordEntitys(null);
			}
			final String jsonString = JSON.toJSONString(sysMessageEntities);
			final Map<String, JSONObject> rsMap = new HashMap<>();
			for (final AreaSeverEntity areaSeverEntity : areaSeverEntityList) {
				JSONObject jsonObject = null;
				try {
					jsonObject = ProxyConnExec.synchronismUpdateSysMessageToCloudBase(jsonString, areaSeverEntity);
				} catch (ConnectException e) {
					jsonObject = new JSONObject();
					jsonObject.put("msgDesc", "连接服务器失败！");
					jsonObject.put("opStatus", "1");
				}
				rsMap.put(areaSeverEntity.getServerName(), jsonObject);
			}
			logger.debug("这是返回给前端的数据  ：" + rsMap);
			return ajaxReturnMap(OP_STATUS_SUCCESS, "", rsMap);

		} catch (Exception e) {
			logErr(e);
			return ajaxReturnMap(OP_STATUS_FAILD, returnMsg(ConfigCodeConstant.UNKNOWN_ERR), null);
		}
	}

	/**
	 * 条件查询，返回所有的查询结果
	 * 
	 * @param sysMsgVo
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/list")
	public Map<String, Object> listSysMsg(SysMsgVo sysMsgVo) {
		try {
			List<SysMessageEntity> list = null;// 保存查询结果
			List<Object> paramList = new ArrayList<Object>();
			String hql = " from SysMessageEntity where 1 = 1 ";

			Date beginTime = sysMsgVo.getBeginTime();
			Date endTime = sysMsgVo.getEndTime();
			// 拼接查询条件
			if (sysMsgVo.getSysMessageEntity() != null) {
				SysMessageEntity sysMessageEntity = sysMsgVo.getSysMessageEntity();

				String sysMessageId = sysMessageEntity.getSysMessageId();
				if (StringUtils.isNotBlank(sysMessageId)) {
					hql += " and " + " sysMessageId = ?";
					paramList.add(sysMessageId);
				}
				String title = sysMessageEntity.getTitle();
				if (StringUtils.isNotBlank(title)) {
					hql += " and" + " title like ?";
					paramList.add("%" + title + "%");
				}
				String code = sysMessageEntity.getCode();
				if (StringUtils.isNotBlank(code)) {
					hql += " and " + " code = ?";
					paramList.add(code);
				}
				String payload = sysMessageEntity.getPayload();
				if (StringUtils.isNotBlank(payload)) {
					hql += " and" + " payload like ?";
					paramList.add("%" + payload + "%");
				}
				String redirectUrl = sysMessageEntity.getRedirectUrl();
				if (StringUtils.isNotBlank(redirectUrl)) {
					hql += " and " + " redirectUrl = ?";
					paramList.add(redirectUrl);
				}
				String content = sysMessageEntity.getContent();
				if (StringUtils.isNotBlank(content)) {
					hql += " and " + " content like ?";
					paramList.add("%" + content + "%");
				}
				Integer contentIsEmpty = sysMessageEntity.getContentIsEmpty();
				if (contentIsEmpty != null) {
					hql += " and " + " contentIsEmpty = ?";
					paramList.add(contentIsEmpty);
				}
				Integer state = sysMessageEntity.getState();
				if (state != null) {
					hql += " and " + " state = ?";
					paramList.add(state);
				}
				if (beginTime != null) {
					hql += " and " + " createTime > ?";
					paramList.add(beginTime);
				}
				if (endTime != null) {
					hql += " and " + " createTime < ?";
					paramList.add(endTime);
				}

			}
			list = sysMsgService.find(hql, SysMessageEntity.class, paramList.toArray());
			if (list != null && list.size() > 0) {
				for (SysMessageEntity sysMessageEntity : list) {
					// sysMessageEntity.setSysMassageSendRecordEntitys(null);
					Set<SysMassageSendRecordEntity> sysMassageSendRecordEntitys = sysMessageEntity
							.getSysMassageSendRecordEntitys();
					for (SysMassageSendRecordEntity sysMassageSendRecordEntity : sysMassageSendRecordEntitys) {
						sysMassageSendRecordEntity.setAreaSevers(null);
						sysMassageSendRecordEntity.setSysMessageEntity(null);
					}
				}
			}
			JSONArray parseArray = JSON.parseArray(JSON.toJSONString(list));

			return ajaxReturnMap(OP_STATUS_SUCCESS, "", parseArray);
		} catch (Exception e) {
			logErr(e);
			return ajaxReturnMap(OP_STATUS_FAILD, returnMsg(ConfigCodeConstant.UNKNOWN_ERR), null);
		}
	}

}
